<?php
namespace App\Controller;

use app\BaseController;
use think\cache\driver\Redis;
use think\Response;
class Project extends BaseController
{
    public function __construct(\think\App $app)
    {
        $this->app = $app;
        $this->request = $this->app->request;

        $this->RankModel = new \app\common\model\Rank;
        $this->ProjectModel = new \app\common\model\Project;
        $this->FilesModel = new \app\common\model\Files;
        $this->RelevanceModel = new \app\common\model\Relevance;
        $this->UserModel = new \app\common\model\User;
    }

    //获取项目列表
    public function list()
    {
        if ($this->request->isGet()) {
            $userid = $this->request->param('userid', 0, 'trim');

            $where = [
                'userid' => $userid
            ];
            $projectList = $this->RelevanceModel
                ->with('project')
                ->where($where)
                ->select();

            $prolist = [];
            if (count($projectList) <= 0) {
                return json(error_ful('暂无数据'));
            }

            foreach ($projectList as $key => $item) {
                if ($item !== null && $item['project']['deletetime'] === null && $item['project']['parentid'] === null && $item['project']['protocol'] === 'protected') {

                    unset($item['project']['backage']);

                    array_push($prolist, $item);
                }
                continue;
            }

            // 获取磁盘信息
            $dir = $_SERVER['DOCUMENT_ROOT'];
            $diskInfo = $this->diskInfo($dir);
            $data = [
                'pro_list' => $prolist,
                'disk_info' => $diskInfo
            ];

            // unset($projectList['project']['backage']);
            return json(success_ful('项目列表', $data));
        }
    }

    //新增项目,仅管理员以上可用
    public function create()
    {
        if ($this->request->isGet()) {
            $userid = $this->request->param('userid', 0, 'trim');
            $proname = $this->request->param('proname', '', 'trim');
            $parentid = $this->request->param('parentid', 0, 'trim');
            $protocol = $this->request->param('protocol', 'protected', 'trim');

            $userInfo = $this->UserModel->where('id', $userid)->find();
            if (empty($userInfo)) {
                return json(error_ful('账号不存在'));
            }

            // 判断账号权限
            $rankId = $userInfo['rankid'];
            $auth = $this->RankModel->where('id', $rankId)->value('weigh');
            if ($auth == '1') {
                return json(error_ful('账号无权限'));
            }

            if (empty($proname)) {
                return json(error_ful('项目名称必填'));
            }

            // 判断父级文件夹
            if (!empty($parentid)) {
                $project = $this->ProjectModel->find($parentid);
                if (empty($project)) {
                    return json(error_ful('父级文件夹不存在'));
                }

                $where = [
                    'proid' => $parentid,
                    'userid' => $userid
                ];
                $relevanceInfo = $this->RelevanceModel->where($where)->find();
                if(empty($relevanceInfo) || $relevanceInfo['auth'] != 4){
                    return json(error_ful('权限不足'));
                }

                $protocol = $project['protocol'];
            }

            // 判断文件夹是否存在
            $proInfo = $this->ProjectModel->where(['proname' => $proname, 'userid' => $userid])->find();
            if (!empty($proInfo)) {
                return json(error_ful('项目已存在'));
            }

            $target_dir = rtrim($_SERVER['DOCUMENT_ROOT'], '/') . '/';
            $dir_name = 'uploads/' . bin2hex(random_bytes(16)) . '/';

            $backage = $target_dir . $dir_name;
            // 检测文件夹是否存在
            if (!is_dir($backage)) {
                // 遍历创建文件夹
                mkdir($backage, 0755, true);
            }

            // 开启事务
            $this->ProjectModel->startTrans();
            $this->RelevanceModel->startTrans();

            $data = [
                'userid' => $userid,
                'proname' => $proname,
                'backage' => $dir_name,
                'createtime' => time(),
                'protocol' => $protocol,
                'parentid' => $parentid ?? null
            ];

            $addStatus = $this->ProjectModel->save($data);
            if ($addStatus === false) {
                rmdir($backage);
                return json(error_ful('项目创建失败'));
            }

            // 创建时默认管理员最高权限
            $lastProid = $this->ProjectModel->getLastInsID();
            $superId = $this->RankModel->where('weigh', '99')->value('id');
            $superUserId = $this->UserModel->where('rankid', $superId)->value('id');
            $relevanceDate = [
                [
                    'proid' => $lastProid,
                    'userid' => $userid,
                    'auth' => '4'
                ],
            ];

            $addArr = [
                [
                    'proid' => $lastProid,
                    'userid' => $superUserId,
                    'auth' => '4'
                ]
            ];
            if ($userid != $superUserId) {

                $relevanceDate = array_merge_recursive($relevanceDate, $addArr);
            }

            $relevanceStatus = $this->RelevanceModel->insertAll($relevanceDate);
            if ($relevanceStatus === false) {
                $this->ProjectModel->rollback();
                return json(error_ful('项目创建失败'));
            }

            if ($addStatus === false || $relevanceStatus === false) {
                rmdir($backage);
                $this->ProjectModel->rollback();
                $this->RelevanceModel->rollback();
                return json(error_ful('项目创建失败'));
            } else {
                $this->ProjectModel->commit();
                $this->RelevanceModel->commit();
                return json(success_ful('项目创建成功'));
            }

        }
    }

    //获取项目详情,与获取文件列表相同
    public function info()
    {
        if ($this->request->isGet()) {
            $proid = $this->request->param('proid', 0, 'trim');
            $userid = $this->request->param('userid', 0, 'trim');

            
            if (empty($proid) || empty($userid)) {
                return json(error_ful('账号或项目不存在'));
            }
            $where = [
                'proid' => $proid,
                'userid' => $userid
            ];
            $relevanceInfo = $this->RelevanceModel->where($where)->find();
            if (empty($relevanceInfo)) {
                return json(error_ful('无权访问'));
            }

            $where = ['deletetime' => null, 'proid' => $proid];

            $count = $this->FilesModel->where($where)->count();
            $fileList = $this->FilesModel->where($where)->select();
            if (count($fileList) <= 0) {
                return json(error_ful('暂无文件'));
            } else {
                $data = [
                    'count' => $count,
                    'auth' => $relevanceInfo['auth'],
                    'fileList' => $fileList,
                ];
                return json(success_ful('文件列表', $data));
            }
        }
    }
    //修改项目信息,仅管理员以上可以
    public function update()
    {
        if ($this->request->isGet()) {
            $userid = $this->request->param('userid', 0, 'trim');
            $proid = $this->request->param('proid', null, 'trim');
            $proname = $this->request->param('proname', '', 'trim');
            $protocol = $this->request->param('protocol', '', 'trim');

            // 查看账号权限
            $where = [
                'userid' => $userid,
                'proid' => $proid
            ];
            $auth = $this->RelevanceModel->where($where)->value('auth');

            if ($auth !== '4') {
                return json(error_ful('当前账号无权限'));
            }

            $projectInfo = $this->ProjectModel->where(['id' => $proid, 'deletetime' => null])->find();
            if (empty($projectInfo)) {
                return json(error_ful('文件夹不存在'));
            }

            // 整合数据
            $data = [];
            if (!empty($proname)) {
                $data['proname'] = $proname;
            }
            if (!empty($protocol)) {
                
                $data['protocol'] = $protocol;
                if($protocol !== $projectInfo['protocol']){
                    $data['parentid'] = null;
                }
            }

            $status = $this->ProjectModel->where('id', $proid)->update($data);
            if ($status === false) {
                return json(error_ful('更新失败'));
            } else {
                return json(success_ful('更新成功'));
            }
        }
    }

    //删除项目,仅管理权限以上可用
    public function delete()
    {
        if ($this->request->isGet()) {
            $userid = $this->request->param('userid', 0, 'trim');
            $proid = $this->request->param('proid', '', 'trim');

            // 查看账号权限
            $where = [
                'userid' => $userid,
                'proid' => $proid
            ];
            $auth = $this->RelevanceModel->where($where)->value('auth');

            if ($auth !== '4') {
                return json(error_ful('当前账号无权限'));
            }

            // 查看文件夹是否存在
            $proInfo = $this->ProjectModel->where('id', $proid)->find();
            if (empty($proInfo)) {
                return json(error_ful('文件夹不存在'));
            }
            // 查看文件夹内是否有文件
            // $where = [
            //     'proid' => $proid,
            //     'deletetime' => null
            // ];
            // $files = $this->FilesModel->where($where)->count();
            // if ($files >= 1) {
            //     return json(error_ful('文件夹使用中，无法删除'));
            // }

            // 执行软删除
            $this->ProjectModel->startTrans();
            $status = $this->ProjectModel->where('id', $proid)->update(['deletetime' => time()]);
            if ($status === false) {
                return json(error_ful('删除失败'));
            }

            if (is_dir($proInfo['backage'])) {
                rmdir($proInfo['backage']);
            }
            $this->ProjectModel->commit();
            return json(success_ful('删除成功'));
        }
    }

    // 获取公开文件夹列表
    public function pubproject()
    {
        if ($this->request->isGet()) {
            $where = [
                'protocol' => 'public',
                'parentid' => null,
                'deletetime' => null
            ];
            $pubProject = $this->ProjectModel->where($where)->select();
            if (count($pubProject) <= 0) {
                return json(error_ful('暂无文件'));
            }

            return json(success_ful('公开文件夹', $pubProject));
        }
    }

    // 获取磁盘信息
    protected function diskInfo()
    {

        // $dir = 'D:\\';
        $dir = $_SERVER['DOCUMENT_ROOT'];
        // 获取总空间和可用空间（字节）
        $totalSpace = disk_total_space($dir);
        $freeSpace = disk_free_space($dir);

        if ($totalSpace === false || $freeSpace === false) {
            die("无法获取磁盘信息，请检查目录是否存在或权限是否足够。");
        }

        // 计算已用空间
        $usedSpace = $totalSpace - $freeSpace;


        $diskInfo = [
            // 'totol_space' => $this->formatSize($totalSpace),
            // 'used_space'    => $this->formatSize($usedSpace),
            'free_space' => $this->formatSize($freeSpace)
        ];

        return $diskInfo;
    }

    // 转换为更易读的单位（GB）
    protected function formatSize($bytes)
    {
        if ($bytes >= 1073741824) { // 1GB = 1024^3 字节
            return number_format($bytes / 1073741824, 2) . ' GB';
        } elseif ($bytes >= 1048576) { // 1MB = 1024^2 字节
            return number_format($bytes / 1048576, 2) . ' MB';
        } else {
            return number_format($bytes) . ' B';
        }
    }

    // echo "磁盘总空间：" . formatSize($totalSpace) . "\n";
    // echo "可用空间：" . formatSize($freeSpace) . "\n";
}
